/*
 *    Copyright (c) 2018-2025, haohanwork.com All rights reserved.
 */
package com.haohan.cloud.scm.saleb.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haohan.cloud.scm.api.bill.dto.OrderInfoDTO;
import com.haohan.cloud.scm.api.common.dto.SelfPageMapper;
import com.haohan.cloud.scm.api.constant.NumberPrefixConstant;
import com.haohan.cloud.scm.api.saleb.dto.BuyOrderSqlDTO;
import com.haohan.cloud.scm.api.saleb.entity.BuyOrder;
import com.haohan.cloud.scm.api.saleb.req.BuyOrderReq;
import com.haohan.cloud.scm.api.saleb.req.CountBuyOrderReq;
import com.haohan.cloud.scm.api.saleb.resp.QueryOrderSumAndPriceSumResp;
import com.haohan.cloud.scm.api.salec.resp.OrderMonitorResp;
import com.haohan.cloud.scm.common.tools.util.ScmIncrementUtil;
import com.haohan.cloud.scm.saleb.mapper.BuyOrderMapper;
import com.haohan.cloud.scm.saleb.service.BuyOrderService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 采购单
 *
 * @author haohan
 * @date 2019-05-13 20:34:39
 */
@Service
@AllArgsConstructor
public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderMapper, BuyOrder> implements BuyOrderService {
    private final ScmIncrementUtil scmIncrementUtil;
    private final BuyOrderMapper buyOrderMapper;

    @Override
    public boolean save(BuyOrder entity) {
        if (StrUtil.isEmpty(entity.getBuyId())) {
            String sn = scmIncrementUtil.inrcSnByClass(BuyOrder.class, NumberPrefixConstant.BUY_ORDER_SN_PRE);
            entity.setBuyId(sn);
        }
        entity.setId(null);
        entity.setTenantId(null);
        return retBool(baseMapper.insert(entity));
    }

    @Override
    public List<QueryOrderSumAndPriceSumResp> countBuyOrder(CountBuyOrderReq req) {
        return buyOrderMapper.countBuyOrder(req);
    }

    @Override
    public List<OrderMonitorResp> queryBuyOrderByTime(BuyOrderReq req) {
        return buyOrderMapper.queryBuyOrderByTime(req);
    }

    @Override
    public BuyOrder fetchBySn(String buyOrderSn) {
        return baseMapper.selectList(Wrappers.<BuyOrder>query().lambda()
                .eq(BuyOrder::getBuyId, buyOrderSn)
        ).stream().findFirst().orElse(null);
    }

    @Override
    public IPage<OrderInfoDTO> findExtPage(BuyOrderSqlDTO query) {
        return SelfPageMapper.findPage(query, baseMapper);
    }

    /**
     * 根据来源订单id查询采购单
     *
     * @param sourceOrderId
     * @return
     */
    @Override
    public BuyOrder fetchBySourceOrderId(String sourceOrderId) {
        if (StrUtil.isEmpty(sourceOrderId)) {
            return null;
        }
        return baseMapper.selectList(Wrappers.<BuyOrder>query().lambda()
                .eq(BuyOrder::getGoodsOrderId, sourceOrderId)
        ).stream().findFirst().orElse(null);
    }
}
